In [42]:
sushi_order = ['unagi', 'hamachi', 'otoro']
prices = [6.50, 5.50, 15.75]
print(sushi_order)
print(prices)
You can access a single element in a list by indexing in using brackets. List indexing starts at 0 so to get the first element, you use 0, the second element is 1 and so on.
list[index]
In [12]:
print(sushi_order[0])
print(sushi_order[2])
You can find the length of a list using len
len(list)
In [15]:
print(len(sushi_order))
You can use negative indexing to get the last element of a list
In [20]:
print(sushi_order[-3])
In [21]:
everyones_order = [['california roll'], ['unagi', 'dragon roll'], sushi_order]
print(everyones_order)
To access an element in a nested list, first index to the inner list, then index to the item.
Example:
list_of_lists = [[1,2], [3,4], []]
Acess the first index to the inner list and index to the item
inner_list = list_of_lists[1] # [3,4]
print inner_list[0] # 3
Or even quicker:
list_of_lists[1][0] # 3
1) To get dragon roll from the sushi order, first we get the second element (index 1) then we get the the second item (index 1)
In [22]:
Out[22]:
2) Print california roll from the list everyones_order
:
In [23]:
Out[23]:
3) Print all items from the second person's order
In [25]:
Out[25]:
In [26]:
sushi_order[0] = 'caterpillar roll'
print(sushi_order)
In [32]:
prices[-1] = 21.00
print(prices)
In [34]:
sushi_order
Out[34]:
In [36]:
print(('hamachi' in sushi_order))
In [37]:
if 'otoro' in sushi_order:
print("Big spender!")
You can use some arithmatic operators on lists
The +
operator concatenates two lists
The *
operator duplicates a list that many times
In [24]:
print((sushi_order * 3))
In [38]:
exprep = ['rep'+str(i) for i in range(5)]
exprep
Out[38]:
In [38]:
print((prices + sushi_order))
Note: You can only concatenate lists with lists! If you want to add a "non-list" element you can use the append() function.
In [43]:
newprices = prices.copy()
newprices.append(22)
print(newprices)
In [44]:
prices
Out[44]:
Remember slices from strings? We can also use the slice operator on lists
In [45]:
inexpensive = sushi_order[:2] #takes only the first two elements from list
print(inexpensive)
Don't forget, you can use the for
and in
keywords to loop through a list
In [47]:
for item in sushi_order:
print(("I'd like to order the {}.".format(item)))
print("And hold the wasabi!")
In [52]:
for ind, item in enumerate(sushi_order):
print(("I'd like to order the {0} for {1}.".format(item, prices[ind])))
In [54]:
lots_of_sushi = inexpensive*2
print(lots_of_sushi)
To add an element to a list, you have a few options
the append method adds an element or elements to the end of a list, if you pass it a list, the next element with be a list (making a list of lists)
the extend method takes a list of elements and adds them all to the end, not creating a list of lists
use the +
operator like you saw before
In [69]:
my_sushis = ['maguro', 'rock n roll']
my_sushis.append('avocado roll')
print(my_sushis)
my_sushis.append(['hamachi', 'california roll'])
print(my_sushis)
In [70]:
my_sushis = ['maguro', 'rock n roll']
my_sushis.extend(['hamachi', 'california roll'])
print(my_sushis)
You also have several options for removing elements
the pop method takes the index of the element to remove and returns the value of the element
the remove method takes the value of the element to remove
the del operator deletes the element or slice of the list that you give it
del l[1:]
In [71]:
print(my_sushis)
last_sushi = my_sushis.pop(-1)
print(last_sushi)
In [72]:
my_sushis.remove('maguro')
print(my_sushis)
In [73]:
del my_sushis[1:]
print(my_sushis)
In [ ]:
In [55]:
numbers = [1, 1, 2, 3, 5, 8]
print((max(numbers)))
print((min(numbers)))
print((sum(numbers)))
print((len(numbers)))
In [57]:
sum(numbers)/len(numbers)
Out[57]:
In [62]:
cooked_rolls = ['unagi roll', 'shrimp tempura roll']
my_order = cooked_rolls
my_order.append('hamachi')
print(my_order)
print(cooked_rolls)
To check this, you can use the is
operator to see if both variable refer to the same object
In [63]:
print((my_order is cooked_rolls))
To fix this, you can make a copy of the list using the list function
list
takes a sequence and turns it into a list.
Alternatively you can use the copy()
method: my_order = cooked_rolls.copy()
In [64]:
cooked_rolls = ['unagi roll', 'shrimp tempura roll']
my_order = list(cooked_rolls)
my_order.append('hamachi')
print(my_order)
print(cooked_rolls)
In [65]:
noodles = ('soba', 'udon', 'ramen', 'lo mein', 'somen', 'rice noodle')
print((type(noodles)))
You can create a tuple from any sequence using the tuple
function
In [68]:
sushi_tuple = tuple(my_order)
print(sushi_tuple)
# Remember strings are sequences
maguro = tuple('maguro')
print(maguro)
To create a single element tuple, you need to add a comma to the end of that element (it looks kinda weird)
In [85]:
single_element_tuple = (1,)
print(single_element_tuple)
print((type(single_element_tuple)))
You can use the indexing and slicing you learned for lists the same with tuples.
But, because tuples are immutable, you cannot use the append, pop, del, extend, or remove methods or even assign new values to indexes
In [69]:
print((noodles[0]))
print((noodles[4:]))
In [70]:
# This should throw an error
noodles[0] = 'spaghetti'
To change the values in a tuple, you need to create a new tuple (there is nothing stopping you from assigning it to the same variable, though
In [71]:
print(sushi_tuple)
sushi_tuple = sushi_tuple[1:] + ('california roll',)
print(sushi_tuple)
You can loop through tuples the same way you loop through lists, using for
in
In [72]:
for noodle in noodles:
print(("Yummy, yummy {0} and {1}".format(noodle, 'sushi')))
In [ ]:
In [73]:
print((list(zip([1,2,3], [4,5,6]))))
In [74]:
sushi = ['salmon', 'tuna', 'sea urchin']
prices = [5.5, 6.75, 8]
sushi_and_prices = list(zip(sushi, prices))
sushi_and_prices
Out[74]:
In [101]:
for sushi, price in sushi_and_prices:
print(("The {0} costs ${1}".format(sushi, price)))
In [111]:
exotic_sushi = ['tako', 'toro', 'uni', 'hirame']
for index, item in enumerate(exotic_sushi):
print((index, item))
You are tasked with writing budgeting software, but at this point, things are a mess. You have two files. budget_prices.txt
has a list of costs for each item separated by new lines (\n). budget_items.txt
has a list of the items that were bought. Luckily they are both in order. You need to write a program that will take the files and a value for the overall budget and print out the total spent and how close they are to reaching the budget. In step 2 you will create a new file where the items and prices are in the same document and there is a sum printed out at the end.
file_to_float_list
that takes in a file and returns a list containing a float for each line Hint Make sure to remove the newlines when casting as floats.budget
.prices
.sum
of the prices array and store in a variable called spent
.percent_spent
Print out the results:
Budget: 2000.00 Spent: (amt spent) Percentage Spent: (percent spent)
Bonus Print out a progress bar for the budget. Print out '=' for every 10% spent and '-' for every 10% unspent. =====>-----
file_to_string_list
that takes in a file and returns a list containing a string for each line with newlines removed.file_to_string_list
on budget_items.txt and save the result in a variable called stuff_bought
.stuff_bought
and prices
together and store in a variable called items_and_prices
items_and_prices
and print out the item, then a tab character '\t' and then the price (use string formatting)Print a final line 'Budget\t(budget)'
Bonus Print everything you printed for step 2 into a new file. (Then open the file in excel.)
In [ ]: